<?

add_action('template_redirect', 'protect');

register_nav_menu( 'header', 'Menu Principal' );

function protect() {
	if (!is_user_logged_in()) {
		header('Location: /manut.html');
	}
}

function wp_pagenavi() {
	return 'ligar page nav';
}

function get_cliente() {
	global $wpdb;
	if ($_SESSION['id']) {
		$id = $_SESSION['id'];
		$rsSelect = $wpdb->get_results("select * from wp_cliente where id = '$id' and status = 1");
		return $rsSelect[0];
	}
	return 0;
}

function get_user_info($field) {
	global $wpdb;
	if ($_SESSION['id']) {
		$id = $_SESSION['id'];
		$rsSelect = $wpdb->get_results("select * from wp_cliente where id = '$id' and status = 1");
		return $rsSelect[0]->$field;
	}
	return 0;
}

add_action('get_cliente', 'init');

add_theme_support('post-thumbnails');
add_action('wp_enqueue_scripts', 'jscripts');

function jscripts() {
	wp_enqueue_script('jquery');
	wp_enqueue_script('thickbox');
	wp_enqueue_script('jscripts', get_bloginfo('template_url') . '/js/jscripts.js');
	wp_enqueue_script('maskedinput', get_bloginfo('template_url') . '/js/jquery.maskedinput.min.js');
	wp_enqueue_style('thickbox');
}

function code($chars) {
	$keychars = "abcdefghijkmnpqrstuvwxyz23456789";
	for ($i = 0; $i < $chars; $i++) {
		$randkey .= substr($keychars, rand(1, strlen($keychars)), 1);
	}
	return $randkey;
}

function crop($string, $limit = 30, $append = '..') {

	$chars = array('.', ',', ';', ':', '[', '(', '{');
	$letras = strlen($string);
	if ($letras > $limit) {
		for ($x = 0; $x <= $letras; $x++) {

			$caracteres = substr($string, 0, $x);
			$letra = substr($string, $x, 1);

			if ($x >= $limit && $letra == " ") {
				$x = $letras;
			}
		}
		if (in_array(substr($caracteres, -1, 1), $chars)) {
			$caracteres = substr($caracteres, 0, -1);
		}
		return $caracteres . $append;
	}
	return $string;
}

function mailEnviar($email, $assunto, $corpo) {
	$headers = "content-type: text/html; charset=UTF-8\r\n";
	$headers .= 'Cc: contato@ricardolanes.com.br' . "\r\n";
	wp_mail($email, $assunto, $corpo, $headers);
}

function mailPagamentoConfirmado($nome, $pedido) {
	$corpo = "	<p>
		<font face=\"Verdana\" size=\"2\">
		" . $nome . ",<br />
		O pagamento do seu pedido  <b>" . $pedido . " foi confirmado com sucesso</b>
		<br />
		<br />
		Atenciosamente; <br />
		" . get_bloginfo('name') . "
		</font>
	</p>";
	return $corpo;
}

function get_frete($origem, $destino, $peso = 0.3, $comprimento = 16, $altura = 2, $largura = 11) {

	if (!$destino) {
		return 0;
	}
	// documento
	//http://www.correios.com.br/webServices/PDF/SCPP_manual_implementacao_calculo_remoto_de_precos_e_prazos.pdf
	//

if ($peso < 0.3) {
		$peso = 0.3;
	}
	if ($comprimento < 16) {
		$comprimento = 16;
	}
	if ($altura < 2) {
		$altura = 2;
	}
	if ($altura > 105) {
		$altura = 100;
	}
	if ($largura < 11) {
		$largura = 11;
	}
	if ($largura > 105) {
		$largura = 105;
	}


	$link = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?sCepOrigem={$origem}&sCepDestino={$destino}&nVlPeso={$peso}&nCdFormato=1&nVlComprimento={$comprimento}&nVlAltura={$altura}&nVlLargura={$largura}&nCdServico=41106&StrRetorno=xml";
	$xml = simplexml_load_string(file_get_contents($link));
	//print_r($xml->cServico);
	$arr['preco'] = $xml->cServico->Valor;
	$arr['prazo'] = $xml->cServico->PrazoEntrega;
	return $arr;
}

function get_pagseguro($pedido, $items) {
	global $wpdb;
	$cliente = get_cliente();



	$x = 0;
	if ($cliente) {
		echo $campos = '
<form id="pagseguro" target="pagseguro" action="https://pagseguro.uol.com.br/security/webpagamentos/webpagto.aspx" method="post">
	<input type="hidden" name="email_cobranca" value="breoart@gmail.com" />
	<input type="hidden" name="tipo" value="CP" />
	<input type="hidden" name="moeda" value="BRL" />
	<input type="hidden" name="cliente_nome" value="" />
	<input type="hidden" name="cliente_cep" value="" />
	<input type="hidden" name="cliente_end" value="" />
	<input type="hidden" name="cliente_num" value="" />
	<input type="hidden" name="cliente_compl" value="" />
	<input type="hidden" name="cliente_bairro" value="" />
	<input type="hidden" name="cliente_cidade" value="" />
	<input type="hidden" name="cliente_uf" value="" />
	<input type="hidden" name="cliente_pais" value="" />
	<input type="hidden" name="cliente_ddd" value="" />
	<input type="hidden" name="cliente_tel" value="" />
	<input type="hidden" name="cliente_email" value="' . $cliente->login . '" />
	<input type="hidden" name="ref_transacao" id="ref_transacao" value="' . $pedido['referencia'] . '" />';


		foreach ($items as $produto) {
			$x++;
			echo '
	<input type="hidden" name="id[' . $produto['id'] . ']" value="' . $produto['qtd'] . '" />
	<input type="hidden" name="item_id_' . $x . '" value="' . $produto['id'] . '" />
	<input type="hidden" name="item_descr_' . $x . '" value="' . $produto['nome'] . '" />
	<input type="hidden" name="item_valor_' . $x . '" value="' . $produto['valor'] . '" />
	<input type="hidden" name="item_quant_' . $x . '" value="' . $produto['qtd'] . '" />';
		}
		$x++;
		echo '
	<input type="hidden" name="item_id_' . $x . '" value="1" />
	<input type="hidden" name="item_descr_' . $x . '" value="Frete" />
	<input type="hidden" name="item_valor_' . $x . '" value="' . $pedido['frete'] . '" />
	<input type="hidden" name="item_quant_' . $x . '" value="1" />
	<input type="hidden" name="item_valor_frete" value="' . $pedido['frete'] . '" />';
	}
}

function formatDate($str) {
	if (strpos($str, " ")) {
		$datetime = explode(" ", $str);
		$date = $datetime[0];
		$time = $datetime[1];
	} else {
		$date = $str;
	}

	if (strpos($date, "/")) {
		$data = implode("-", array_reverse(explode("/", $date)));
	} else {
		$data = implode("/", array_reverse(explode("-", $date)));
	}

	if ($time) {
		return $data . " " . $time;
	}
	return $data;
}

function make_filename_hash($filename) {
	$info = pathinfo($filename);
	$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
	$name = basename($filename, $ext);
	return md5($name) . $ext;
}

add_filter('sanitize_file_name', 'make_filename_hash', 10);

function simple_curl($url, $post = array(), $get = array()) {
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	return curl_exec($ch);
}

function get_labels() {
	global $wpdb;
	$label = $wpdb->get_results("SELECT * FROM wp_filters as f WHERE parent IS NULL order by label");
	return $label;
}

function get_post_filter($post_id, $label) {
	global $wpdb;
	//echo "SELECT * FROM wp_post_filter as pf, wp_filters as f WHERE pf.filter_id = f.id_filter and pf.post_id = '$post_id' and parent = '$label'";
	$filtros = $wpdb->get_results("SELECT * FROM wp_post_filter as pf, wp_filters as f WHERE pf.filter_id = f.id_filter and pf.post_id = '$post_id' and parent = '$label'");
	return $filtros;
}

function get_post_filter_id($filter_id) {
	global $wpdb;
	//echo "SELECT * FROM wp_post_filter as pf, wp_filters as f WHERE pf.filter_id = f.id_filter and pf.post_id = '$post_id' and parent = '$label'";
	$filtros = $wpdb->get_results("SELECT * FROM wp_post_filter as pf, wp_filters as f WHERE pf.filter_id = f.id_filter and pf.id = '$filter_id'");
	return $filtros[0];
}